package com.beaven.imserver.net.factory;

import com.beaven.imserver.net.bean.db.Category;
import com.beaven.imserver.net.bean.db.User;
import com.beaven.imserver.net.utils.HibUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * author: Beaven
 * time: 2017/5/23 9:51
 */
public class CategoryFactory {

  // 创建分组
  public static Category create(String name, User owner) {
    Category category = new Category();
    category.setName(name.trim());
    category.setOwnerId(owner.getId());
    category.setOwner(owner);
    return HibUtil.query(session -> {
      session.save(category);
      return category;
    });
  }

  // 查询分组列表
  public static List<Category> queryList(User self) {
    return HibUtil.query(session -> {
      session.load(self, self.getId());
      Set<Category> categories = self.getCategories();
      return new ArrayList<>(categories);
    });
  }

  // 查询单一分组
  public static Category queryByName(User self, String name) {
    return HibUtil.query(session -> {
      session.load(self, self.getId());
      return (Category) session.createQuery("from Category where name=:name and ownerId=:ownerId")
          .setParameter("name", name)
          .setParameter("ownerId", self.getId()).uniqueResult();
    });
  }

  public static Category queryById(User self, String id) {
    return HibUtil.query(session -> {
      session.load(self, self.getId());
      return (Category) session.createQuery("from Category where id=:id")
          .setParameter("id", id)
          .uniqueResult();
    });
  }
}
